﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Boxes : MonoBehaviour
{
    Rigidbody2D boxRb2d;

    [Header("Layer")]
    public LayerMask PlayerLayer;
    public LayerMask Ground;
    public Transform Pos;

    public bool canBePush;

    public bool isHitGround;

    [Header("碰撞体属性")]
    Collider2D boxCollider2D;
    private float xOffset, yOffset;

    public float CheckLength;
    void Start()
    {
        boxCollider2D = GetComponent<Collider2D>();
        boxRb2d = GetComponent<Rigidbody2D>();
        xOffset = boxCollider2D.bounds.size.x;
        yOffset = boxCollider2D.bounds.size.y;

    }

    void Update()
    {
        PhysicsCheck();
    }
    void PhysicsCheck()
    {
        Vector2 pos = transform.position;

        RaycastHit2D[] hitRight = Physics2D.RaycastAll(pos + new Vector2(xOffset / 2, -yOffset / 3), Vector2.right, CheckLength, PlayerLayer);
        Debug.DrawRay(pos + new Vector2(xOffset / 2, -yOffset / 3), Vector2.right * CheckLength, Color.red);

        RaycastHit2D[] hitLeft = Physics2D.RaycastAll(pos - new Vector2(xOffset / 1.5f, yOffset / 3), Vector2.left, CheckLength, PlayerLayer);
        Debug.DrawRay(pos - new Vector2(xOffset / 1.5f, yOffset / 3), Vector2.right * CheckLength, Color.red);

        isHitGround =  Physics2D.Raycast(Pos.position, Vector2.down ,CheckLength, Ground);
        Debug.DrawRay(Pos.position, Vector2.down * CheckLength, Color.red);


        if (!isHitGround)
        {
            boxRb2d.bodyType = RigidbodyType2D.Dynamic;
        }
        else if (isHitGround)
        {
            if (hitLeft.Length == 2 || hitRight.Length == 2)
            {
                boxRb2d.bodyType = RigidbodyType2D.Dynamic;
            }
            else if (hitLeft.Length != 2 || hitRight.Length != 2 )
            {
                boxRb2d.bodyType = RigidbodyType2D.Static;
            }
        }
    }
}
